﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Threading;
using NetClientFramework.Helper;

namespace Demo.Snake
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : System.Windows.Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            LogHelper.Init();
            base.OnStartup(e);
            ServicePointManager.DefaultConnectionLimit = 512;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

            Current.DispatcherUnhandledException += App_OnDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            LogHelper.Info("OnStartup");
        }

        /// <summary>
        /// UI线程抛出全局异常事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                LogHelper.Error(e.Exception.Message, e.Exception);
                e.Handled = true;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message, ex);
            }
        }

        /// <summary>
        /// 非UI线程抛出全局异常事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                if (e.ExceptionObject is Exception exception)
                {
                    // 非UI线程抛出全局异常事件处理
                    LogHelper.Error(exception.Message, exception);
                }
            }
            catch (Exception ex)
            {
                //不可恢复的非UI线程全局异常
                LogHelper.Error(ex.Message, ex);
                //MessageBox.Show("应用程序发生不可恢复的异常，将要退出！");
            }
        }
    }
}
